package org.charles.android.easlogger;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Currency;
import java.util.Date;

public class EasloggerService extends Service {
    Process mProcess;
    static final String fileStoreMainDir = "/sdcard";
    static final String fileStoreSubDir = "eas_log";


    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        log("onStartCommand");
        super.onStartCommand(intent, flags, startId);
        if (mProcess != null) {
            log("mProcess exists");
            return Service.START_NOT_STICKY;
        }
        try {
            mProcess = Runtime.getRuntime().exec("logcat -v time -f " + getLogPath());
        } catch (IOException e) {
            log("IOException caught: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            log("Exception caught: " + e.getMessage());
        }
        return Service.START_STICKY;
    }

    private void log(String s) {
        Log.i("Charles_TAG", this.getClass().getSimpleName() + " :: " + s);
    }

    private String getLogPath() {
        verifyFileStore();
        StringBuffer logPath = new StringBuffer();
        logPath.append(fileStoreMainDir + "/" + fileStoreSubDir + "/");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String curentDateandTime = sdf.format(new Date(System.currentTimeMillis()));
        logPath.append(curentDateandTime);
        logPath.append(".txt");
        log(logPath.toString());
        return logPath.toString();
    }

    private boolean verifyFileStore() {
        boolean ret = false;
        try {
           File dir = new File(fileStoreMainDir);
           if(dir.exists() && dir.isDirectory() && dir.canWrite()) {
              dir = new File(dir.getName(), fileStoreSubDir);
              if(!dir.exists())
                 dir.mkdir();  // throws
              ret = dir.exists() && dir.isDirectory() && dir.canWrite();
           }
        } catch (SecurityException e) {
           log(e.toString());
        }
        return ret;
     }

    @Override
    public void onDestroy() {
        log("onDestory");
        super.onDestroy();
        if (mProcess != null) {
            mProcess.destroy();
        }
    }
}
